package com.atguigu.gmall.realtime.utils;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.realtime.common.GmallConfig;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CellUtil;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.util.Bytes;

import java.io.IOException;
import java.util.List;

/**
 * @author Felix
 * @date 2023/7/4
 * 操作hbase的工具类
 */
public class HbaseUtil {
    //获取连接
    public static Connection getConnection() {
        try {
            Configuration conf = new Configuration();
            // 配置 Zookeeper
            conf.set("hbase.zookeeper.quorum", "hadoop102,hadoop103,hadoop104");
            Connection conn = ConnectionFactory.createConnection(conf);
            return conn;
        } catch (IOException e) {
            throw new RuntimeException();
        }
    }

    //关闭连接
    public static void closeConnection(Connection conn) {
        if (conn != null && !conn.isClosed()) {
            try {
                conn.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    //获取支持异步的连接
    public static AsyncConnection getAsyncConnection() {
        try {
            Configuration conf = new Configuration();
            // 配置 Zookeeper
            conf.set("hbase.zookeeper.quorum", "hadoop102,hadoop103,hadoop104");
            // Connection conn = ConnectionFactory.createConnection(conf);
            AsyncConnection conn = ConnectionFactory.createAsyncConnection(conf).get();
            return conn;
        } catch (Exception e) {
            throw new RuntimeException();
        }
    }
    //关闭支持异步的连接
    public static void closeAsyncConnection(AsyncConnection asyncConnection){
        if(asyncConnection != null && !asyncConnection.isClosed()){
            try {
                asyncConnection.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    //删表
    public static void dropTable(Connection conn, String namespace, String tableName) {
        try (Admin admin = conn.getAdmin()) {
            //判断要删除的表是否存在
            TableName tableNameObj = TableName.valueOf(namespace, tableName);
            if (!admin.tableExists(tableNameObj)) {
                System.out.println("要删除的" + namespace + ":" + tableName + "表不存在");
                return;
            }
            System.out.println("从Hbase中删除表:" + namespace + "_" + tableName);
            admin.disableTable(tableNameObj);
            admin.deleteTable(tableNameObj);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 建表
     *
     * @param conn      和Hbase的连接对象
     * @param namespace 表空间
     * @param tableName 表名
     * @param families  列族
     */
    public static void createTable(Connection conn, String namespace, String tableName, String... families) {
        if (families.length < 1) {
            System.out.println("建表的时候至少需要指定一个列族");
            return;
        }

        try (Admin admin = conn.getAdmin()) {
            TableName tableNameObj = TableName.valueOf(namespace, tableName);
            if (admin.tableExists(tableNameObj)) {
                System.out.println("要创建的表" + namespace + ":" + tableName + "已经存在");
                return;
            }

            System.out.println("在Hbase中创建表:" + namespace + "_" + tableName);
            TableDescriptorBuilder tableDescriptorBuilder = TableDescriptorBuilder.newBuilder(tableNameObj);
            for (String family : families) {
                ColumnFamilyDescriptor columnFamilyDescriptor
                    = ColumnFamilyDescriptorBuilder.newBuilder(Bytes.toBytes(family)).build();
                tableDescriptorBuilder.setColumnFamily(columnFamilyDescriptor);
            }
            admin.createTable(tableDescriptorBuilder.build());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //从Hbase表中删除数据
    public static void delRow(Connection conn, String namespace, String tableName, String rowKey) throws IOException {
        TableName tableNameObj = TableName.valueOf(namespace, tableName);
        Table table = conn.getTable(tableNameObj);
        Delete delete = new Delete(Bytes.toBytes(rowKey));
        table.delete(delete);
        table.close();
    }

    //向Hbase表中put数据
    public static void putRow(Connection conn, String namespace, String tableName, String rowKey,
                              String family, String[] columns, String[] values) throws IOException {
        TableName tableNameObj = TableName.valueOf(namespace, tableName);
        Table table = conn.getTable(tableNameObj);
        Put put = new Put(Bytes.toBytes(rowKey));
        for (int i = 0; i < columns.length; i++) {
            String column = columns[i];
            String value = values[i];
            if (value != null) {
                put.addColumn(Bytes.toBytes(family), Bytes.toBytes(column), Bytes.toBytes(value));
            }
        }
        table.put(put);
        table.close();
    }

    //获取从hbase中读取字典维度数据创建动态表的建表语句
    public static String getBaseDicLookUpDDL() {
        return "CREATE TABLE base_dic (\n" +
            " rowkey string,\n" +
            " info ROW<dic_name string>,\n" +
            " PRIMARY KEY (rowkey) NOT ENFORCED\n" +
            ") " + getHbaseDDL("dim_base_dic");
    }

    //获取hbase连接器连接属性
    public static String getHbaseDDL(String tableName) {
        return "WITH (\n" +
            " 'connector' = 'hbase-2.2',\n" +
            " 'table-name' = '" + GmallConfig.HBASE_NAMESPACE + ":" + tableName + "',\n" +
            " 'zookeeper.quorum' = 'hadoop102,hadoop103,hadoop104',\n" +
            " 'lookup.cache' = 'PARTIAL',\n" +
            " 'lookup.partial-cache.max-rows' = '300',\n" +
            " 'lookup.partial-cache.expire-after-write' = '1 hour',\n" +
            " 'lookup.partial-cache.expire-after-access' = '1 hour'\n" +
            ")";
    }

    //从hbase表中查询一行维度数据
    public static JSONObject getDimInfoFromHbase(Connection conn,
                                                String namespace,
                                                String tableName,
                                                String rowkey){
        TableName tableNameObj = TableName.valueOf(namespace, tableName);
        try (Table table = conn.getTable(tableNameObj)){
            Get get = new Get(Bytes.toBytes(rowkey));
            Result result = table.get(get);
            List<Cell> cells = result.listCells();
            if(cells != null && cells.size() > 0){
                JSONObject jsonObj = new JSONObject();
                for (Cell cell : cells) {
                    String columnName = Bytes.toString(CellUtil.cloneQualifier(cell));
                    String columnValue = Bytes.toString(CellUtil.cloneValue(cell));
                    jsonObj.put(columnName,columnValue);
                }
                return jsonObj;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    //以异步的方式，从hbase表中查询一行维度数据
    public static JSONObject getDimInfoFromHbaseByAsync(AsyncConnection conn,
                                                        String namespace,
                                                        String tableName,
                                                        String rowkey){
        TableName tableNameObj = TableName.valueOf(namespace, tableName);
        AsyncTable<AdvancedScanResultConsumer> table = conn.getTable(tableNameObj);
        Get get = new Get(Bytes.toBytes(rowkey));
        try {
            Result result = table.get(get).get();
            List<Cell> cells = result.listCells();
            if(cells != null && cells.size() > 0){
                JSONObject dimJsonObj = new JSONObject();
                for (Cell cell : cells) {
                    String columnName = Bytes.toString(CellUtil.cloneQualifier(cell));
                    String columnValue = Bytes.toString(CellUtil.cloneValue(cell));
                    dimJsonObj.put(columnName,columnValue);
                }
                return dimJsonObj;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    public static void main(String[] args) {
        Connection conn = getConnection();
        System.out.println(getDimInfoFromHbase(conn, GmallConfig.HBASE_NAMESPACE, "dim_sku_info", "1"));
    }
}
